#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件清理脚本
用于删除项目中的冗余文件和临时文件
"""

import os
import shutil
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='cleanup_log.txt',
    filemode='w'
)

# 主目录路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 要删除的文件列表
to_delete_files = [
    # 根目录下的冗余数据库文件
    os.path.join(BASE_DIR, 'test.db'),
    os.path.join(BASE_DIR, 'test_backup_20251102_133158.db'),
    os.path.join(BASE_DIR, 'test_backup_20251102_133253.db'),
    os.path.join(BASE_DIR, 'lease_contract.db'),
    os.path.join(BASE_DIR, 'rent_management.db'),
    os.path.join(BASE_DIR, 'rent_management.db.backup_1762074876'),
    
    # 日志和报告文件
    os.path.join(BASE_DIR, 'mock_data_generator.log'),
    os.path.join(BASE_DIR, 'cleanup_report_20251102_131946.txt'),
    os.path.join(BASE_DIR, 'verify_zero_amount_report_20251102_133158.txt'),
    os.path.join(BASE_DIR, 'verify_zero_amount_report_20251102_133254.txt'),
    
    # backup目录下的测试备份文件
    os.path.join(BASE_DIR, 'backup', 'test_backup_20251101_005844.db'),
    os.path.join(BASE_DIR, 'backup', 'test_auto_backup_20251101_010555.db'),
    os.path.join(BASE_DIR, 'backup', 'test_backup_20251102_133842.db'),
]

# 记录成功和失败的文件
successfully_deleted = []
failed_to_delete = []
total_cleaned_size = 0

def delete_file(file_path):
    """
    删除单个文件并记录结果
    """
    global total_cleaned_size
    try:
        if os.path.exists(file_path):
            # 获取文件大小
            if os.path.isfile(file_path):
                file_size = os.path.getsize(file_path)
                total_cleaned_size += file_size
            
            # 删除文件
            os.remove(file_path)
            logging.info(f"已成功删除文件: {file_path} ({file_size/1024:.2f} KB)")
            successfully_deleted.append(file_path)
            return True
        else:
            logging.warning(f"文件不存在: {file_path}")
            return False
    except Exception as e:
        logging.error(f"删除文件失败: {file_path}. 错误: {str(e)}")
        failed_to_delete.append((file_path, str(e)))
        return False

def main():
    """
    主函数，执行文件清理操作
    """
    print(f"开始清理项目文件... ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})")
    logging.info("开始执行文件清理操作")
    
    # 遍历并删除文件
    for file_path in to_delete_files:
        delete_file(file_path)
    
    # 生成清理报告
    print("\n===== 清理报告 =====")
    print(f"成功删除的文件数: {len(successfully_deleted)}")
    print(f"删除失败的文件数: {len(failed_to_delete)}")
    print(f"清理的总空间: {total_cleaned_size/(1024*1024):.2f} MB")
    
    if successfully_deleted:
        print("\n成功删除的文件:")
        for file in successfully_deleted:
            print(f"  - {os.path.basename(file)}")
    
    if failed_to_delete:
        print("\n删除失败的文件:")
        for file, error in failed_to_delete:
            print(f"  - {os.path.basename(file)}: {error}")
    
    logging.info(f"清理操作完成。成功: {len(successfully_deleted)}, 失败: {len(failed_to_delete)}, 释放空间: {total_cleaned_size/(1024*1024):.2f} MB")
    print(f"\n清理操作已完成。详情请查看 cleanup_log.txt 文件。")

if __name__ == "__main__":
    main()
